package com.lianjing.sh.acceleo.controller.tool.query;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.emf.common.util.EList;
import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.Include;
import org.eclipse.uml2.uml.UseCase;

public class UseCaseService{
	
	/**
	 * getIncludeTargetPaths
	 */
	public List<List<UseCase>> getIncludeTargetPaths(UseCase useCase){
		List<List<UseCase>> container = new ArrayList<>();
		List<UseCase> oldColumnContainer = new ArrayList<>();
			oldColumnContainer.add(useCase);
		getIncludeTargetPaths_S(useCase, container, oldColumnContainer);
		return container;
	}
	
	/**
	 * 递归获取路径目标
	 */
	private void getIncludeTargetPaths_S(UseCase useCase, List<List<UseCase>> container, List<UseCase> oldColumnContainer) {
		for(Include include : useCase.getIncludes()){
			// 取得 useCaseTarget
			UseCase useCaseTarget = getUseCaseTarget(include);
			if(null == useCaseTarget){
				break;
			}
			// 加入到列
			List<UseCase> columnContainer = new ArrayList<>();
				columnContainer.addAll(oldColumnContainer);
				columnContainer.add(useCaseTarget);
			getIncludeTargetPaths_S(useCaseTarget, container, columnContainer);
			if(useCaseTarget.getIncludes().isEmpty()){
				container.add(columnContainer);
			}
		}
	}
	
	/**
	 * 取得 useCaseTarget
	 */
	private UseCase getUseCaseTarget(Include include){
		EList<Element> targets = include.getTargets();
		if(targets.isEmpty()){
			return null;
		}
		Element target = targets.get(0);
		if(!(target instanceof UseCase)){
			return null;
		}
		return (UseCase)target;
	}
	
	/**
	 * List<UseCase> 的顺序 ： a->b->c
	 */
	public List<Include> getIncludePath(List<UseCase> useCasePath){
		List<Include> path = new ArrayList<>();
		for(int i =0 ; i+1 < useCasePath.size() ; i++){
			Include include = getBetweenInclude(useCasePath.get(i), useCasePath.get(i+1));
			if(null != include){
				path.add(include);
			}
		}
		return path;
	}
	
	/**
	 * getBetweenInclude
	 */
	public Include getBetweenInclude(UseCase source, UseCase target){
		for(Include item : source.getIncludes()){
			if(item.getTargets().contains(target)){
				return item;
			}
		}
		return null;
	}

//	/**
//	 * navigationChainsDropSelf
//	 */
//	public List<List<UseCase>> includeTargetPaths navigationChainsDropSelf(List<List<UseCase>> navigationChains){
//		List<List<UseCase>> newChains = new ArrayList<>();
//		for(List<UseCase> paths : navigationChains){
//			List<UseCase> newPaths = new ArrayList<>();
//			int i = 0;
//			for(UseCase path : paths){
//				if(i>0){
//					newPaths.add(path);
//				}
//				i++;
//			}
//			//
//			if(!newPaths.isEmpty()){
//				newChains.add(newPaths);
//			}
//		}
//		return newChains;
//	}

}
